package com.sf.fy.uav.applet.config;

import com.sf.fy.uav.common.enums.ServicePrefixEnum;
import com.sf.fy.uav.common.utils.LocalCache;
import com.sf.fy.uav.common.utils.RedisPrefixKey;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author LTQ
 * ws://localhost:8080/ws/Tom
 */
@ServerEndpoint("/home/{token}")
@Component
public class MySocket {
    private String currentUser;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 用于存放所有在线客户端
     */
    public static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接打开时执行
     *
     * @param token
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("token") String token, Session session) {
        clients.put(token, session);
        List<String> strings = (List<String>) LocalCache.getCache(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.SOCKET_TOKEN);
        if (ObjectUtils.isEmpty(strings)) {
            strings = new ArrayList<>();
        }
        strings.add(token);
        sendMessage(session, "已建立连接");
        LocalCache.addCache(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.SOCKET_TOKEN, strings);
    }


    /**
     * 收到消息时执行
     *
     * @param message
     * @param session
     * @return
     */
    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println(currentUser + "：" + message);
        return currentUser + "：" + message;
    }


    /**
     * 收到消息时执行
     *
     * @param message
     * @return
     */
    public void onMessageToWebAdminer(String message) {
        // 将无序集合保存到Redis中
        List<String> tokens = (List<String>) LocalCache.getCache(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.SOCKET_TOKEN);
        LocalCache.cache.remove(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.SOCKET_TOKEN);
        if (!ObjectUtils.isEmpty(tokens)) {
            tokens = tokens.stream().distinct().collect(Collectors.toList());
            List<String> newTokens = new ArrayList<>();
            tokens.forEach(token -> {
                Session session = clients.get(token);
                if (!ObjectUtils.isEmpty(session)) {
                    Boolean isSend = true;
                    try {
                        sendMessage(session, message);
                    } catch (Exception e) {
                        isSend = false;
                    }
                    if (isSend) {
                        newTokens.add(token);
                        LocalCache.addCache(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.SOCKET_TOKEN, newTokens);
                    }
                }
            });
        }

    }


    /**
     * 连接关闭时执行
     *
     * @param session
     * @param closeReason
     */
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("用户" + session.getId() + "已退出！");
    }

    @OnError
    public void onError(Throwable error) {
        System.out.println("onError......" + error.getMessage());

    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}